#include "log.h"

#include "HandlerThread.h"
#include <unistd.h>
#include <utils/Looper.h>

namespace android
{
    class MainMessageHandler;
    bool mShouldQuit;
    sp<Looper> threadLooper;
    sp<Looper> mainLooper;
    sp<MainMessageHandler> mainMessageHandler;

    class ThreadMessageHandler : public MessageHandler
    {
    public:
        virtual void handleMessage(const Message &message)
        {
            LOGD("ThreadMessageHandler message->what = %d", message.what);
            // do something what you want
            usleep(10 * 1000);
            // HandlerThread程调用mainLooper的sendMessage，发送一个Message()到主线程
            mainLooper->sendMessage(mainMessageHandler, Message(message.what));
        }
    };

    class MainMessageHandler : public MessageHandler
    {
    public:
        virtual void handleMessage(const Message &message)
        {
            LOGD("MainMessageHandler message->what = %d", message.what);
            // 结束标志位
            if (message.what == 5)
            {
                mShouldQuit = true;
            }
        }
    };

    int test()
    {
        LOGD("start test");
        // 开启`HandlerThread`线程
        sp<HandlerThread> mHandlerThread = new HandlerThread();
        LOGD("HandlerThread start");
        mHandlerThread->start("VMS.NATIVE_LOOP");
        // 从线程中获取`threadLooper`对象
        threadLooper = mHandlerThread->getLooper();
        // new ThreadMessageHandler()里面重载了handleMessage(),会在消息来后回调
        sp<ThreadMessageHandler> threadMessageHandler = new ThreadMessageHandler();
        // 主线程调用threadLooper的sendMessage，发送一个Message(1)到HandlerThread线程
        threadLooper->sendMessage(threadMessageHandler, Message(1));
        // 发送一个延时消息
        threadLooper->sendMessageDelayed(ms2ns(100), threadMessageHandler, Message(2));
        threadLooper->sendMessage(threadMessageHandler, Message(3));

        // 主线程构造一个mainLooper
        mainLooper = Looper::prepare(0);
        // new MainMessageHandler()里面重载了handleMessage(),会在消息来后回调
        mainMessageHandler = new MainMessageHandler();
        // 主线程调用mainLooper的sendMessage，发送一个Message(4)到自己线程
        mainLooper->sendMessage(mainMessageHandler, Message(4));
        // 主线程调用mainLooper的sendMessageDelayed，发送一个延时Message(5)到自己线程
        mainLooper->sendMessageDelayed(ms2ns(1000), mainMessageHandler, Message(5));

        // 主线程开启循环等待消息
        while (true)
        {
            if (mShouldQuit)
            {
                break;
            }
            mainLooper->pollOnce(-1);
        }
        // 结束HandlerThread
        mHandlerThread->quit();
        LOGD("test end");
        return 0;
    }
} // namespace android

int main(int argc, char const *argv[])
{
    android::test();
    return 0;
}
